import React, { useEffect, useState, useCallback } from 'react';
import { Card, Spin, Empty, Table, Button, Tooltip } from 'antd';
import ReactECharts from 'echarts-for-react';
import { getUnit, getTopComplexityMethods } from '../../../services/unit';
import { getTreemapFiles, getVolumeTopClassesAsFiles, getVolumeTopMethods } from '../../../services/statistics';
import { buildFileLink, formatRelativePath as formatRelativePathUtil, convertSshToHttp } from '../../../utils/gitUrlUtils';
import { CodeDuplicationTable } from '../components';

interface CodeScaleAnalysisProps {
    unitId: string;
}

// 生成完整项目结构的模拟数据
const generateMockScaleData = () => {
    const files = [
        // Java源代码文件
        { path: 'src/main/java/com/codeknowledge/controller/UserController.java', lines: 2340 },
        { path: 'src/main/java/com/codeknowledge/controller/OrderController.java', lines: 1890 },
        { path: 'src/main/java/com/codeknowledge/controller/ProductController.java', lines: 1450 },
        { path: 'src/main/java/com/codeknowledge/controller/PaymentController.java', lines: 1200 },
        { path: 'src/main/java/com/codeknowledge/controller/AdminController.java', lines: 980 },
        { path: 'src/main/java/com/codeknowledge/controller/ReportController.java', lines: 760 },
        { path: 'src/main/java/com/codeknowledge/controller/BaseController.java', lines: 330 },
        { path: 'src/main/java/com/codeknowledge/service/UserService.java', lines: 3200 },
        { path: 'src/main/java/com/codeknowledge/service/OrderService.java', lines: 2850 },
        { path: 'src/main/java/com/codeknowledge/service/ProductService.java', lines: 2400 },
        { path: 'src/main/java/com/codeknowledge/service/PaymentService.java', lines: 2100 },
        { path: 'src/main/java/com/codeknowledge/service/NotificationService.java', lines: 1800 },
        { path: 'src/main/java/com/codeknowledge/service/EmailService.java', lines: 1450 },
        { path: 'src/main/java/com/codeknowledge/service/AuthService.java', lines: 1200 },
        { path: 'src/main/java/com/codeknowledge/service/CacheService.java', lines: 620 },
        { path: 'src/main/java/com/codeknowledge/repository/UserRepository.java', lines: 1890 },
        { path: 'src/main/java/com/codeknowledge/repository/OrderRepository.java', lines: 1560 },
        { path: 'src/main/java/com/codeknowledge/repository/ProductRepository.java', lines: 1330 },
        { path: 'src/main/java/com/codeknowledge/repository/PaymentRepository.java', lines: 980 },
        { path: 'src/main/java/com/codeknowledge/repository/ConfigRepository.java', lines: 720 },
        { path: 'src/main/java/com/codeknowledge/repository/LogRepository.java', lines: 300 },
        { path: 'src/main/java/com/codeknowledge/model/User.java', lines: 780 },
        { path: 'src/main/java/com/codeknowledge/model/Order.java', lines: 650 },
        { path: 'src/main/java/com/codeknowledge/model/Product.java', lines: 590 },
        { path: 'src/main/java/com/codeknowledge/model/Payment.java', lines: 480 },
        { path: 'src/main/java/com/codeknowledge/model/Category.java', lines: 420 },
        { path: 'src/main/java/com/codeknowledge/model/Address.java', lines: 320 },
        { path: 'src/main/java/com/codeknowledge/model/BaseEntity.java', lines: 240 },
        { path: 'src/main/java/com/codeknowledge/config/DatabaseConfig.java', lines: 450 },
        { path: 'src/main/java/com/codeknowledge/config/SecurityConfig.java', lines: 380 },
        { path: 'src/main/java/com/codeknowledge/config/RedisConfig.java', lines: 320 },
        { path: 'src/main/java/com/codeknowledge/config/WebConfig.java', lines: 290 },
        { path: 'src/main/java/com/codeknowledge/Application.java', lines: 120 },
        { path: 'src/test/java/com/codeknowledge/controller/UserControllerTest.java', lines: 850 },
        { path: 'src/test/java/com/codeknowledge/service/UserServiceTest.java', lines: 920 },
        { path: 'src/test/java/com/codeknowledge/repository/UserRepositoryTest.java', lines: 680 },
        { path: 'src/test/java/com/codeknowledge/ApplicationTest.java', lines: 240 },
        { path: 'src/main/resources/application.yml', lines: 120 },
        { path: 'src/main/resources/application-dev.yml', lines: 85 },
        { path: 'src/main/resources/application-prod.yml', lines: 95 },
        { path: 'src/main/resources/logback-spring.xml', lines: 180 },
        { path: 'src/main/resources/banner.txt', lines: 12 },
        { path: 'src/main/resources/static/css/style.css', lines: 450 },
        { path: 'src/main/resources/static/js/main.js', lines: 320 },
        { path: 'src/main/resources/static/js/utils.js', lines: 180 },
        { path: 'src/main/resources/templates/index.html', lines: 85 },
        { path: 'src/main/resources/templates/error.html', lines: 45 },
        { path: 'src/main/resources/db/migration/V1__Init_database.sql', lines: 280 },
        { path: 'src/main/resources/db/migration/V2__Add_user_table.sql', lines: 95 },
        { path: 'src/test/resources/application-test.yml', lines: 65 },
        { path: 'src/test/resources/test-data.sql', lines: 150 },
        { path: 'pom.xml', lines: 320 },
        { path: 'README.md', lines: 180 },
        { path: '.gitignore', lines: 45 },
        { path: 'Dockerfile', lines: 35 },
        { path: 'docker-compose.yml', lines: 85 },
        { path: 'config/checkstyle.xml', lines: 150 },
        { path: 'config/spotbugs-exclude.xml', lines: 85 },
        { path: 'scripts/build.sh', lines: 65 },
        { path: 'scripts/deploy.sh', lines: 120 },
        { path: 'scripts/start.sh', lines: 45 },
        { path: 'scripts/stop.sh', lines: 25 },
        { path: 'docs/API.md', lines: 450 },
        { path: 'docs/DEPLOYMENT.md', lines: 280 },
        { path: 'docs/CHANGELOG.md', lines: 320 },
        { path: 'frontend/src/App.js', lines: 280 },
        { path: 'frontend/src/index.js', lines: 45 },
        { path: 'frontend/src/components/Header.js', lines: 120 },
        { path: 'frontend/src/components/Footer.js', lines: 85 },
        { path: 'frontend/src/utils/api.js', lines: 180 },
        { path: 'frontend/package.json', lines: 65 },
        { path: 'frontend/README.md', lines: 95 }
    ];
    return { files };
};

const CodeScaleAnalysis: React.FC<CodeScaleAnalysisProps> = ({ unitId }) => {
    const [scaleData, setScaleData] = useState<any>(null);
    const [loading, setLoading] = useState(false);
    const [volumeTopData, setVolumeTopData] = useState<any>(null);
    const [volumeTopLoading, setVolumeTopLoading] = useState(false);
    const [unitInfo, setUnitInfo] = useState<any>(null);
    const [topComplexityMethods, setTopComplexityMethods] = useState<any[]>([]);
    const [complexityLoading, setComplexityLoading] = useState(false);

    // 构建Git代码仓库链接的工具函数（兼容SSH和HTTP格式）
    const buildGiteeLink = (filePath: string, startLine?: number, endLine?: number): string => {
        if (!unitInfo?.gitRepoUrl || !filePath) return '';
        const branch = unitInfo.currentBranch || unitInfo.defaultBranch || 'master';
        return buildFileLink(unitInfo.gitRepoUrl, filePath, branch, startLine, endLine);
    };

    // 使用公共的路径格式化函数
    const formatRelativePath = (filePath?: string) => {
        if (!filePath) return '';
        const repoInfo = unitInfo?.gitRepoUrl ? convertSshToHttp(unitInfo.gitRepoUrl) : null;
        const repoName = repoInfo?.repo || '';
        return formatRelativePathUtil(filePath, repoName);
    };

    const truncatePath = (path: string, maxLength: number = 80) => {
        if (!path) return '';
        if (path.length <= maxLength) return path;
        return `...${path.slice(-maxLength)}`;
    };

    const renderPathCell = (filePath?: string) => {
        const relative = formatRelativePath(filePath);
        const display = truncatePath(relative || filePath || '');
        return (
            <Tooltip title={relative || filePath || '-'} placement="topLeft">
                <span style={{
                    display: 'inline-block',
                    maxWidth: '100%',
                    whiteSpace: 'nowrap',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    color: '#475569'
                }}>
                    {display}
                </span>
            </Tooltip>
        );
    };

    // 加载单元信息
    const loadUnitInfo = useCallback(async () => {
        if (!unitId) return;
        try {
            const response = await getUnit(unitId);
            const dataRes = (response && response.data) ? response.data : response;
            setUnitInfo(dataRes || null);
        } catch (error: any) {
            console.error('加载单元信息失败:', error);
            setUnitInfo(null);
        }
    }, [unitId]);

    // 加载代码规模数据
    const loadScaleData = useCallback(async () => {
        if (!unitId) return;
        setLoading(true);
        try {
            const response = await getTreemapFiles(unitId);
            console.log('API response:', response);

            let fileList: any[] = [];
            if (response && typeof response === 'object') {
                if ('code' in response && response.code === 0 && Array.isArray(response.data)) {
                    fileList = response.data;
                } else if (Array.isArray(response)) {
                    fileList = response;
                } else {
                    console.warn('未识别的响应格式:', response);
                    setScaleData(generateMockScaleData());
                    return;
                }
            } else if (Array.isArray(response)) {
                fileList = response;
            }

            if (Array.isArray(fileList) && fileList.length > 0) {
                const transformedFiles = fileList.map((item: any) => ({
                    path: item.path,
                    lines: item.lines,
                    size: item.size,
                    language: item.lang
                }));
                setScaleData({ files: transformedFiles });
                console.log('Loaded treemap files from API:', {
                    count: transformedFiles.length,
                    sample: transformedFiles[0]
                });
            } else {
                console.warn('树图文件数据为空或格式错误:', fileList);
                setScaleData(generateMockScaleData());
            }
        } catch (error) {
            console.error('加载代码规模数据失败:', error);
            setScaleData(generateMockScaleData());
        } finally {
            setLoading(false);
        }
    }, [unitId]);

    // 加载体量Top数据
    const loadVolumeTopData = useCallback(async () => {
        if (!unitId) return;
        setVolumeTopLoading(true);
        try {
            const [filesResponse, methodsResponse] = await Promise.all([
                getVolumeTopClassesAsFiles(unitId),
                getVolumeTopMethods(unitId)
            ]);

            let filesData: any[] = [];
            let methodsData: any[] = [];

            if (filesResponse && typeof filesResponse === 'object') {
                if ('code' in filesResponse && filesResponse.code === 0 && Array.isArray(filesResponse.data)) {
                    filesData = filesResponse.data;
                } else if (Array.isArray(filesResponse)) {
                    filesData = filesResponse;
                }
            }

            if (methodsResponse && typeof methodsResponse === 'object') {
                if ('code' in methodsResponse && methodsResponse.code === 0 && Array.isArray(methodsResponse.data)) {
                    methodsData = methodsResponse.data;
                } else if (Array.isArray(methodsResponse)) {
                    methodsData = methodsResponse;
                }
            }

            setVolumeTopData({
                files: filesData || [],
                methods: methodsData || []
            });

            console.log('Loaded volume top data from API:', {
                files: filesData?.length || 0,
                methods: methodsData?.length || 0
            });
        } catch (error: any) {
            console.error('加载体量Top数据失败:', error);
            setVolumeTopData({ files: [], methods: [] });
        } finally {
            setVolumeTopLoading(false);
        }
    }, [unitId]);

    // 加载高复杂度方法数据
    const loadTopComplexityMethods = useCallback(async () => {
        if (!unitId) return;
        setComplexityLoading(true);
        try {
            const response = await getTopComplexityMethods(unitId, 10);
            let methodsData: any[] = [];
            if (response && typeof response === 'object') {
                if ('code' in response && response.code === 0 && Array.isArray(response.data)) {
                    methodsData = response.data;
                } else if ('success' in response && response.success && Array.isArray(response.data)) {
                    methodsData = response.data;
                } else if (Array.isArray(response)) {
                    methodsData = response;
                }
            }
            setTopComplexityMethods(methodsData || []);
            console.log('Loaded top complexity methods from API:', methodsData?.length || 0);
        } catch (error: any) {
            console.error('加载高复杂度方法数据失败:', error);
            setTopComplexityMethods([]);
        } finally {
            setComplexityLoading(false);
        }
    }, [unitId]);

    useEffect(() => {
        if (unitId) {
            loadUnitInfo();
            loadScaleData();
            loadVolumeTopData();
            loadTopComplexityMethods();
        }
    }, [unitId, loadUnitInfo, loadScaleData, loadVolumeTopData, loadTopComplexityMethods]);

    // treemap 层级视觉（参考 ECharts Disk Usage 示例）
    const getLevelOption = () => ([
        {
            itemStyle: { borderColor: '#777', borderWidth: 0, gapWidth: 1 },
            upperLabel: { show: false }
        },
        {
            itemStyle: { borderColor: '#555', borderWidth: 4, gapWidth: 1 },
            emphasis: { itemStyle: { borderColor: '#ddd' } }
        },
        {
            colorSaturation: [0.35, 0.6],
            itemStyle: { borderWidth: 4, gapWidth: 1, borderColorSaturation: 0.6 }
        }
    ]);

    // 计算目录下的文件数量
    const countFiles = (node: any): number => {
        if (node.isFile) return 1;
        if (!node.children) return 0;
        return node.children.reduce((count: number, child: any) => count + countFiles(child), 0);
    };

    // 准备树图数据（基于真实 API 数据的文件系统路径层级结构）
    const getTreemapData = () => {
        if (!scaleData || !scaleData.files) return [];

        const buildFileSystemHierarchy = () => {
            const root = { name: 'project', children: [] as any[], value: 0 };

            scaleData.files.forEach((file: any) => {
                const filePath = file.path;
                const pathParts = filePath.split('/').filter((part: string) => part.length > 0);
                const lines = file.lines || 0;
                let current = root;

                for (let i = 0; i < pathParts.length; i++) {
                    const part = pathParts[i];
                    const isLastLevel = (i === pathParts.length - 1);
                    const currentPath = pathParts.slice(0, i + 1).join('/');

                    let existing = current.children.find((child: any) => child.name === part);
                    if (!existing) {
                        existing = {
                            name: part,
                            fullPath: currentPath,
                            children: isLastLevel ? undefined : [],
                            value: isLastLevel ? lines : 0,
                            isFile: isLastLevel,
                            isDirectory: !isLastLevel,
                            level: i,
                            ...(isLastLevel && {
                                fileName: part,
                                originalLines: lines,
                                fileExtension: part.includes('.') ? part.split('.').pop() || '' : '',
                                language: file.language || '',
                                fileSize: file.size || 0
                            })
                        };
                        current.children.push(existing);
                    } else if (isLastLevel) {
                        existing.value += lines;
                        existing.originalLines = (existing.originalLines || 0) + lines;
                    }
                    current = existing;
                }
            });

            const calculateValues = (node: any): number => {
                if (node.isFile) return node.value || 0;
                if (node.children && node.children.length > 0) {
                    node.value = node.children.reduce((sum: number, child: any) => sum + calculateValues(child), 0);
                }
                return node.value || 0;
            };

            calculateValues(root);

            console.log('Generated file system treemap data from real API:', {
                totalFiles: scaleData.files.length,
                rootChildren: root.children.length,
                sampleFile: scaleData.files[0],
                sampleNode: root.children[0],
                rootValue: root.value
            });

            return root.children || [];
        };

        return buildFileSystemHierarchy();
    };

    // 获取树图配置
    const getTreemapOption = () => {
        const data = getTreemapData();

        if (!data || data.length === 0) {
            console.warn('No treemap data available');
            return {
                title: {
                    text: '暂无数据',
                    left: 'center',
                    top: 'middle'
                }
            };
        }

        return {
            tooltip: {
                trigger: 'item',
                formatter: (params: any) => {
                    const data = params.data;
                    if (data.isFile) {
                        const lines = [
                            `<strong>${data.name}</strong>`,
                            `路径: ${data.fullPath}`,
                            `代码行数: <span style="color: #1890ff">${params.value.toLocaleString()}</span>`
                        ];
                        if (data.fileSize !== undefined && data.fileSize > 0) {
                            const sizeKB = (data.fileSize / 1024).toFixed(1);
                            lines.push(`文件大小: <span style="color: #52c41a">${sizeKB} KB</span>`);
                        }
                        if (data.language) {
                            lines.push(`语言: <span style="color: #722ed1">${data.language}</span>`);
                        }
                        return lines.join('<br/>');
                    } else if (data.isDirectory) {
                        const fileCount = countFiles(data);
                        return `<strong>${data.name}/</strong><br/>路径: ${data.fullPath}<br/>包含文件: ${fileCount} 个<br/>总代码行数: <span style="color: #1890ff">${params.value.toLocaleString()}</span>`;
                    } else {
                        return `<strong>${data.fullPath || data.name}</strong><br/>代码行数: <span style="color: #1890ff">${params.value.toLocaleString()}</span>`;
                    }
                },
                backgroundColor: 'rgba(255, 255, 255, 0.95)',
                borderColor: '#ddd',
                borderWidth: 1,
                textStyle: { fontSize: 12 }
            },
            series: [{
                name: '代码体量',
                type: 'treemap',
                id: 'code-size',
                universalTransition: true,
                data: data,
                width: '100%',
                height: '100%',
                roam: false,
                nodeClick: false,
                colorMappingBy: 'value',
                color: [
                    '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
                    '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf',
                    '#aec7e8', '#ffbb78', '#98df8a', '#ff9896', '#c5b0d5'
                ],
                breadcrumb: { show: false },
                label: {
                    show: true,
                    formatter: (params: any) => {
                        if (params.data.isFile) {
                            const fileName = params.data.name;
                            return fileName.length > 20 ? fileName.substring(0, 17) + '...' : fileName;
                        } else if (params.data.isDirectory) {
                            return params.data.name;
                        }
                        return params.data.name;
                    },
                    fontSize: (params: any) => {
                        const area = params.rect.width * params.rect.height;
                        if (area > 15000) return 14;
                        if (area > 8000) return 12;
                        if (area > 3000) return 10;
                        if (area > 1000) return 8;
                        return 0;
                    },
                    color: '#333'
                },
                upperLabel: {
                    show: true,
                    height: 20,
                    color: '#fff',
                    fontWeight: 'bold',
                    formatter: (params: any) => {
                        if (params.data.isDirectory) {
                            return `${params.data.name}/`;
                        }
                        return params.data.name;
                    },
                    backgroundColor: 'rgba(0,0,0,0.7)'
                },
                visibleMin: 30,
                leafDepth: null,
                itemStyle: {
                    borderColor: '#fff',
                    borderWidth: 2,
                    gapWidth: 1,
                    shadowColor: 'rgba(0,0,0,0.1)',
                    shadowBlur: 2
                },
                levels: getLevelOption()
            }]
        };
    };

    // 加载状态
    if (loading) {
        return (
            <div style={{ textAlign: 'center', padding: '40px' }}>
                <Spin size="large" />
                <div style={{ marginTop: '16px' }}>加载代码规模数据中...</div>
            </div>
        );
    }

    if (!scaleData) {
        return (
            <div style={{ textAlign: 'center', padding: '40px' }}>
                <Empty description="暂无代码规模数据" />
            </div>
        );
    }

    // 组装文件级别数据Top10
    const topFilesData = (() => {
        if (volumeTopData?.files && Array.isArray(volumeTopData.files)) {
            return volumeTopData.files
                .sort((a: any, b: any) => (b.totalLines || 0) - (a.totalLines || 0))
                .map((item: any, idx: number) => {
                    const fileName = item.fileName || item.filePath?.split('/').pop() || 'Unknown';
                    const directoryPath = item.filePath ?
                        item.filePath.substring(0, item.filePath.lastIndexOf('/')) || '/' : '';
                    return {
                        key: item.filePath || `file_${idx}`,
                        rank: idx + 1,
                        fileName: fileName,
                        directoryPath: directoryPath,
                        filePath: item.filePath || '',
                        fullPath: item.filePath || '',
                        totalLines: item.totalLines || 0,
                        codeLines: item.codeLines || 0,
                        language: item.language || '',
                        fileSize: item.fileSize || 0
                    };
                });
        }
        return [];
    })();

    // 组装方法级别数据Top10
    const topMethodsData = (() => {
        if (volumeTopData?.methods && Array.isArray(volumeTopData.methods)) {
            return volumeTopData.methods.map((method: any, idx: number) => {
                let displayPackageName = method.packageName || '';
                if (displayPackageName.startsWith('java.')) {
                    displayPackageName = displayPackageName.substring(5);
                }
                return {
                    key: `${method.filePath}#${method.methodName}` || `method_${idx}`,
                    rank: idx + 1,
                    methodName: method.methodName || 'Unknown',
                    className: method.className || '',
                    packageName: displayPackageName,
                    filePath: method.filePath || '',
                    fullName: method.methodFullName || `${method.className}#${method.methodName}`,
                    totalLines: method.totalLines || 0,
                    codeLines: method.codeLines || 0,
                    startLine: method.startLine || 0,
                    endLine: method.endLine || 0,
                    accessFlag: method.accessFlag || '',
                    isEntry: method.isEntry || false,
                    serviceName: method.serviceName || '',
                    serviceType: method.serviceType || ''
                };
            });
        }
        return [];
    })();

    // 格式化日期
    const formatDate = (dateStr: string) => {
        if (!dateStr) return '';
        try {
            const date = new Date(dateStr);
            return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit'
            });
        } catch {
            return dateStr;
        }
    };

    return (
        <div>
            <Card
                title="代码全局视图"
                extra={
                    <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                        <Button
                            size="small"
                            onClick={() => {
                                const canvas = document.querySelector('.echarts-for-react canvas') as HTMLCanvasElement;
                                if (canvas) {
                                    const url = canvas.toDataURL('image/png');
                                    const link = document.createElement('a');
                                    link.download = '代码全局视图.png';
                                    link.href = url;
                                    link.click();
                                }
                            }}
                        >
                            下载图片
                        </Button>
                    </div>
                }
                style={{ marginBottom: '12px' }}
            >
                <div style={{
                    border: '1px solid #f0f0f0',
                    borderRadius: '8px',
                    padding: '8px',
                    backgroundColor: '#fafafa'
                }}>
                    <ReactECharts
                        option={getTreemapOption()}
                        style={{ width: '100%', height: '600px' }}
                        opts={{ renderer: 'canvas' }}
                    />
                </div>
            </Card>

            {/* 代码行数 Top 10 表格 */}
            <div style={{ display: 'flex', gap: '12px' }}>
                {/* 文件级别 Top 10 */}
                <Card
                    title="文件级别 Top 10 (按总行数降序)"
                    style={{ flex: 1, height: '600px', display: 'flex', flexDirection: 'column' }}
                    bodyStyle={{ padding: '12px', flex: 1, overflow: 'auto' }}
                >
                    {volumeTopLoading ? (
                        <div style={{ textAlign: 'center', padding: '20px' }}>
                            <Spin />
                            <div style={{ marginTop: '8px', fontSize: '12px' }}>加载中...</div>
                        </div>
                    ) : topFilesData.length > 0 ? (
                        <Table
                            dataSource={topFilesData}
                            rowKey="key"
                            pagination={false}
                            size="small"
                            showHeader={true}
                            style={{ fontSize: '12px' }}
                            columns={[
                                {
                                    title: '排名',
                                    dataIndex: 'rank',
                                    key: 'rank',
                                    width: 45,
                                    align: 'center' as const,
                                    render: (rank: number) => (
                                        <div style={{
                                            width: 18,
                                            height: 18,
                                            borderRadius: '50%',
                                            backgroundColor: rank <= 3 ? '#ff4d4f' : rank <= 6 ? '#faad14' : '#52c41a',
                                            color: 'white',
                                            display: 'flex',
                                            alignItems: 'center',
                                            justifyContent: 'center',
                                            fontSize: 9,
                                            fontWeight: 'bold',
                                            margin: '0 auto'
                                        }}>
                                            {rank}
                                        </div>
                                    )
                                },
                                {
                                    title: '文件名',
                                    dataIndex: 'fileName',
                                    key: 'fileName',
                                    render: (text: string, record: any) => {
                                        const giteeLink = buildGiteeLink(record.filePath);
                                        return giteeLink ? (
                                            <a
                                                href={giteeLink}
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                style={{ fontWeight: 'bold', color: '#1890ff', fontSize: '12px', textDecoration: 'none' }}
                                                onMouseEnter={(e) => (e.target as HTMLElement).style.textDecoration = 'underline'}
                                                onMouseLeave={(e) => (e.target as HTMLElement).style.textDecoration = 'none'}
                                                title={`查看 ${text} 的源代码`}
                                            >
                                                {text}
                                            </a>
                                        ) : (
                                            <div style={{ fontWeight: 'bold', color: '#1890ff', fontSize: '12px' }}>
                                                {text}
                                            </div>
                                        );
                                    }
                                },
                                {
                                    title: '目录路径',
                                    dataIndex: 'directoryPath',
                                    key: 'directoryPath',
                                    render: (text: string) => (
                                        <div style={{ color: '#475569' }}>
                                            {text || '/'}
                                        </div>
                                    )
                                },
                                {
                                    title: '总行数',
                                    dataIndex: 'totalLines',
                                    key: 'totalLines',
                                    width: 60,
                                    align: 'center' as const,
                                    render: (value: number) => (
                                        <span style={{ fontWeight: '600', color: '#1890ff', fontSize: '12px' }}>{value || 0}</span>
                                    )
                                },
                            ]}
                        />
                    ) : (
                        <div style={{ textAlign: 'center', padding: '20px' }}>
                            <Empty description="暂无文件数据" image={Empty.PRESENTED_IMAGE_SIMPLE} />
                        </div>
                    )}
                </Card>

                {/* 方法级别 Top 10 */}
                <Card
                    title="方法级别 Top 10 (按总行数降序)"
                    style={{ flex: 1, height: '600px', display: 'flex', flexDirection: 'column' }}
                    bodyStyle={{ padding: '12px', flex: 1, overflow: 'auto' }}
                >
                    {volumeTopLoading ? (
                        <div style={{ textAlign: 'center', padding: '20px' }}>
                            <Spin />
                            <div style={{ marginTop: '8px', fontSize: '12px' }}>加载中...</div>
                        </div>
                    ) : topMethodsData.length > 0 ? (
                        <Table
                            dataSource={topMethodsData}
                            rowKey="key"
                            pagination={false}
                            size="small"
                            showHeader={true}
                            style={{ fontSize: '12px' }}
                            columns={[
                                {
                                    title: '排名',
                                    dataIndex: 'rank',
                                    key: 'rank',
                                    width: 45,
                                    align: 'center' as const,
                                    render: (rank: number) => (
                                        <div style={{
                                            width: 18,
                                            height: 18,
                                            borderRadius: '50%',
                                            backgroundColor: rank <= 3 ? '#722ed1' : rank <= 6 ? '#1890ff' : '#13c2c2',
                                            color: 'white',
                                            display: 'flex',
                                            alignItems: 'center',
                                            justifyContent: 'center',
                                            fontSize: 9,
                                            fontWeight: 'bold',
                                            margin: '0 auto'
                                        }}>
                                            {rank}
                                        </div>
                                    )
                                },
                                {
                                    title: '方法名',
                                    dataIndex: 'methodName',
                                    key: 'methodName',
                                    render: (text: string, record: any) => {
                                        const giteeLink = buildGiteeLink(record.filePath, record.startLine, record.endLine);
                                        return giteeLink ? (
                                            <a
                                                href={giteeLink}
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                style={{ fontWeight: 'bold', color: '#722ed1', fontSize: '12px', textDecoration: 'none' }}
                                                onMouseEnter={(e) => (e.target as HTMLElement).style.textDecoration = 'underline'}
                                                onMouseLeave={(e) => (e.target as HTMLElement).style.textDecoration = 'none'}
                                                title={`查看方法 ${text} 的源代码${record.startLine ? ` (第${record.startLine}行)` : ''}`}
                                            >
                                                {text}
                                            </a>
                                        ) : (
                                            <div style={{ fontWeight: 'bold', color: '#722ed1', fontSize: '12px' }}>
                                                {text}
                                            </div>
                                        );
                                    }
                                },
                                {
                                    title: '文件路径',
                                    dataIndex: 'filePath',
                                    key: 'filePath',
                                    render: (text: string) => renderPathCell(text)
                                },
                                {
                                    title: '总行数',
                                    dataIndex: 'totalLines',
                                    key: 'totalLines',
                                    width: 60,
                                    align: 'center' as const,
                                    render: (value: number) => (
                                        <span style={{ fontWeight: '600', color: '#722ed1', fontSize: '12px' }}>{value || 0}</span>
                                    )
                                },
                                {
                                    title: '代码行',
                                    dataIndex: 'codeLines',
                                    key: 'codeLines',
                                    width: 60,
                                    align: 'center' as const,
                                    render: (value: number) => (
                                        <span style={{ fontWeight: '600', color: '#52c41a', fontSize: '12px' }}>{value || 0}</span>
                                    )
                                }
                            ]}
                        />
                    ) : (
                        <div style={{ textAlign: 'center', padding: '20px' }}>
                            <Empty description="暂无方法数据" image={Empty.PRESENTED_IMAGE_SIMPLE} />
                        </div>
                    )}
                </Card>
            </div>

            <div style={{ display: 'flex', gap: '12px', marginTop: '12px', alignItems: 'stretch' }}>
                <div style={{ flex: 1 }}>
                    <Card
                        title="高复杂度方法 Top 10 (按圈复杂度降序)"
                        bodyStyle={{ padding: '12px' }}
                        style={{ height: '100%' }}
                    >
                        {complexityLoading ? (
                            <div style={{ textAlign: 'center', padding: '20px' }}>
                                <Spin />
                                <div style={{ marginTop: '8px', fontSize: '12px' }}>加载中...</div>
                            </div>
                        ) : topComplexityMethods.length > 0 ? (
                            <Table
                                dataSource={topComplexityMethods.map((method: any, index: number) => ({
                                    key: method.id || index,
                                    rank: index + 1,
                                    className: method.className,
                                    methodName: method.methodName,
                                    complexity: method.cyclomaticComplexity,
                                    filePath: method.filePath,
                                    startLine: method.startLine,
                                    endLine: method.endLine,
                                    totalLine: method.totalLine,
                                    gitLastEditTime: method.gitLastEditTime,
                                    gitLastEditEmp: method.gitLastEditEmp,
                                    gitLastEditMsg: method.gitLastEditMsg,
                                    gitLastEditCommitId: method.gitLastEditCommitId
                                }))}
                                rowKey="key"
                                pagination={false}
                                size="small"
                                showHeader={true}
                                style={{ fontSize: '12px' }}
                                columns={[
                                    {
                                        title: '排名',
                                        dataIndex: 'rank',
                                        key: 'rank',
                                        width: 45,
                                        align: 'center' as const,
                                        render: (rank: number) => (
                                            <div style={{
                                                width: 18,
                                                height: 18,
                                                borderRadius: '50%',
                                                backgroundColor: rank <= 3 ? '#ff4d4f' : rank <= 6 ? '#fa8c16' : '#fadb14',
                                                color: 'white',
                                                display: 'flex',
                                                alignItems: 'center',
                                                justifyContent: 'center',
                                                fontSize: 9,
                                                fontWeight: 'bold',
                                                margin: '0 auto'
                                            }}>
                                                {rank}
                                            </div>
                                        )
                                    },
                                    {
                                        title: '方法名',
                                        dataIndex: 'methodName',
                                        key: 'methodName',
                                        render: (text: string, record: any) => {
                                            const giteeLink = buildGiteeLink(record.filePath, record.startLine, record.endLine);
                                            return giteeLink ? (
                                                <a
                                                    href={giteeLink}
                                                    target="_blank"
                                                    rel="noopener noreferrer"
                                                    style={{ fontWeight: 'bold', color: '#ff4d4f', fontSize: '12px', textDecoration: 'none' }}
                                                    onMouseEnter={(e) => (e.target as HTMLElement).style.textDecoration = 'underline'}
                                                    onMouseLeave={(e) => (e.target as HTMLElement).style.textDecoration = 'none'}
                                                    title={`查看方法 ${text} 的源代码${record.startLine ? ` (第${record.startLine}行)` : ''}`}
                                                >
                                                    {text}
                                                </a>
                                            ) : (
                                                <div style={{ fontWeight: 'bold', color: '#ff4d4f', fontSize: '12px' }}>
                                                    {text}
                                                </div>
                                            );
                                        }
                                    },
                                    {
                                        title: '类名',
                                        dataIndex: 'className',
                                        key: 'className',
                                        render: (text: string) => (
                                            <div style={{ fontSize: '10px', color: '#666' }}>
                                                {text}
                                            </div>
                                        )
                                    },
                                    {
                                        title: '圈复杂度',
                                        dataIndex: 'complexity',
                                        key: 'complexity',
                                        width: 80,
                                        align: 'center' as const,
                                        render: (value: number) => {
                                            let color = '#52c41a';
                                            if (value > 20) color = '#ff4d4f';
                                            else if (value > 10) color = '#fa8c16';
                                            else if (value > 5) color = '#fadb14';
                                            return (
                                                <span style={{ fontWeight: '600', color: color, fontSize: '12px' }}>
                                                    {value || 0}
                                                </span>
                                            );
                                        }
                                    },
                                    {
                                        title: '方法行数',
                                        dataIndex: 'totalLine',
                                        key: 'totalLine',
                                        width: 80,
                                        align: 'center' as const,
                                        render: (value: number) => (
                                            <span style={{ fontWeight: '600', color: '#1890ff', fontSize: '12px' }}>
                                                {value || 0}
                                            </span>
                                        )
                                    },
                                    {
                                        title: '最后变更信息',
                                        key: 'gitLastEdit',
                                        width: 280,
                                        render: (_: any, record: any) => {
                                            if (!record.gitLastEditTime && !record.gitLastEditEmp && !record.gitLastEditMsg) {
                                                return <span style={{ color: '#999', fontSize: '11px' }}>-</span>;
                                            }
                                            return (
                                                <div style={{ fontSize: '11px' }}>
                                                    <div style={{ color: '#666', marginBottom: '2px' }}>
                                                        <span style={{ color: '#1890ff', fontWeight: '500' }}>
                                                            {record.gitLastEditEmp || '未知'}
                                                        </span>
                                                        {record.gitLastEditTime && (
                                                            <span style={{ color: '#999', marginLeft: '6px' }}>
                                                                {formatDate(record.gitLastEditTime)}
                                                            </span>
                                                        )}
                                                    </div>
                                                    {record.gitLastEditMsg && (
                                                        <div
                                                            style={{
                                                                color: '#999',
                                                                overflow: 'hidden',
                                                                textOverflow: 'ellipsis',
                                                                whiteSpace: 'nowrap',
                                                                maxWidth: '260px'
                                                            }}
                                                            title={record.gitLastEditMsg}
                                                        >
                                                            {record.gitLastEditMsg}
                                                        </div>
                                                    )}
                                                </div>
                                            );
                                        }
                                    }
                                ]}
                            />
                        ) : (
                            <div style={{ textAlign: 'center', padding: '20px' }}>
                                <Empty description="暂无高复杂度方法数据" image={Empty.PRESENTED_IMAGE_SIMPLE} />
                            </div>
                        )}
                    </Card>
                </div>
                <CodeDuplicationTable
                    unitId={unitId}
                    gitRepoUrl={unitInfo?.gitRepoUrl}
                    currentBranch={unitInfo?.currentBranch || unitInfo?.defaultBranch}
                    containerStyle={{ flex: 1, marginTop: 0 }}
                />
            </div>
        </div>
    );
};

export default CodeScaleAnalysis;
